package com.stdz.counter.utils;


import com.stdz.counter.constant.MeterConstant;
import com.stdz.counter.entity.MeterTask;
import com.stdz.counter.service.DeviceService;
import com.stdz.counter.service.MeterTaskService;
import de.re.easymodbus.exceptions.ConnectionException;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author peanut
 */
public class SchedulingRunnable implements Runnable{

    private static final Logger LOG = LoggerFactory.getLogger(SchedulingRunnable.class);

    private String cron;

    private Integer meterId;

    private MeterTaskService meterTaskService;

    private DeviceService deviceService;

    public SchedulingRunnable(String cron, Integer meterId, MeterTaskService meterTaskService, DeviceService deviceService) {
        this.cron = cron;
        this.meterId = meterId;
        this.meterTaskService = meterTaskService;
        this.deviceService = deviceService;
    }

    @SneakyThrows
    @Override
    public void run() {
        // 执行任务
        LOG.debug(meterId + "的表达式是：" + cron);
        LOG.debug("执行任务");
        // 清零
        try {
            deviceService.clear(meterId + "");
        } catch (ConnectionException e) {
            LOG.error("当前的异常是：{}" + e.getMessage());
            throw new ConnectionException("请检查端口链接");
        } catch (Exception e) {
            throw new Exception("请检查端口链接");
        }

        // 如果是单次的话  就修改状态
        MeterTask meterTask = meterTaskService.findByMeterId(meterId);
        if (MeterConstant.BIT_ZERO_FLAG.equals(meterTask.getType())) {
            meterTaskService.updateByMeterId(meterId);
        }
    }
}
